﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Solidi;

namespace Solidi
{
	/// <summary>
	/// Thread safe
	/// </summary>
	public sealed class AutoDependencyRegistry : IDependencyRegistry
	{
		private IDependencyRegistry _registry;

		public AutoDependencyRegistry(IDependencyRegistry registry)
		{
			if (registry == null)
			{
				throw new ArgumentNullException("registry");
			}

			_registry = registry;
		}

		public void Add(IEnumerable<IDependency> dependencies)
		{
			_registry.Add(dependencies);
		}

		public IEnumerable<IDependency> Find(IDependencyKey key, Func<IEnumerable<IDependency>> dependencyFactory)
		{
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

			Type type = key.Type;

			if (key.Name == null && type.IsClass && !type.IsSubclassOf(typeof(Delegate)))
			{
				return _registry.Find(key, () => new IDependency[] { new AutoDependency(key) });
			}
			
			return _registry.Find(key, dependencyFactory);
		}
	}
}
